//
//  PhotoViewController.m
//  Auditory
//
//  Created by 寒竹子 on 15/4/30.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//  照片浏览

#define KBorder 15.0f
#define IMG_W   290.0f

#import "PhotoViewController.h"
#import "PicModel.h"
#import "UIViewController+MMSpinner.h"
#import "FTWCache.h"

@interface PhotoViewController ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIImageView * imageView;
@property (nonatomic, strong) UIScrollView * scrollView;
@property (nonatomic, assign) BOOL isScale; // 是否缩放

@end

@implementation PhotoViewController


- (instancetype)initWithPicModel:(PicModel *)model
{
    if (self = [super init]) {
        _model = model;
    }
    
    return self;
}

/**
 * @brief  设置导航
 *
 * @param
 * @return
 */
- (void)setupNav
{
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UILabel * titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100.0f, 25.0f)];
    titleView.textAlignment = NSTextAlignmentCenter;
    titleView.font = TextFont(18.0f);
    titleView.text = @"图集详情";
    titleView.textColor = RGB(100, 100, 100, 1.0f);
    
    [self addNavigationWithTitle:nil leftItem:backItem rightItem:nil titleView:titleView];
}

/**
 * @brief  初始化UI
 *
 * @param
 * @return
 */
- (void)setupUI
{
    self.view.backgroundColor = RGB(0, 0, 0, 1.0f);
    
    [self setupNav];
    
    // 创建用于滑动的ScrollView
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64.0f)];
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake(self.view.frame.size.width + 20.0f, self.view.frame.size.height - 64.0f + 20.0f);
    _scrollView.bounces = YES;
    _scrollView.backgroundColor = RGB(0, 0, 0, 1.0f);
    [self.view addSubview:_scrollView];
    
    CGFloat img_w = [_model.image_width floatValue];
    CGFloat img_h = [_model.image_height floatValue];
    CGFloat image_H = IMG_W / img_w * img_h;
    
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - IMG_W) / 2.0f, KBorder, IMG_W, image_H)];
    _imageView.userInteractionEnabled = YES;
    
    _imageView.center = _scrollView.center;
    [_scrollView addSubview:_imageView];
    
    // 标题
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 25.0f - 64.0f - 10.0f, self.view.frame.size.width, 25.0f)];
    titleLabel.font = TextFont(14.0f);
    titleLabel.text = _model.desc.length > 0? _model.desc:_model.colum;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];
    
    [self downloadImage];
    
    // 添加双击手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 2;
    tap.delegate = self;
    [_imageView addGestureRecognizer:tap];
}

/**
 * @brief  双击放大图片
 *
 * @param
 * @return
 */
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (!_isScale) {
        // 放大图片
        [UIView animateWithDuration:.4f animations:^{
            _imageView.transform = CGAffineTransformScale(_imageView.transform, 1.5, 1.5);
        } completion:^(BOOL finished) {
            _isScale = YES;
            tap.numberOfTapsRequired = 1;
        }];
    }else {
        // 还原图片
        [UIView animateWithDuration:.4f animations:^{
            _imageView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
        } completion:^(BOOL finished) {
            _isScale = NO;
            tap.numberOfTapsRequired = 2;
        }];
    }
}

/**
 * @brief  下载图片
 *
 * @param
 * @return
 */
- (void)downloadImage
{
    [self addMMSpinner];
    
    NSData * data = [FTWCache objectForKey:_model.image_url];
    if (data) {
        // 本地有数据
        [self removeMMSpinner];
        UIImage * image = [UIImage imageWithData:data scale:1.0f];
        _imageView.image = image;
    }else {
        // 本地没有数据
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            UIImage * image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_model.image_url]]];
            
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self removeMMSpinner];
                    _imageView.image = image;
                    // 保存到本地
                    [FTWCache setObject:UIImageJPEGRepresentation(image, 1.0f) forKey:_model.image_url];
                });
            }
        });
    }
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self removeMMSpinner];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

#pragma mark - UITapGestureDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
